/**
 * 飞书文件预览
 */
import type { NextApiRequest, NextApiResponse } from 'next';
import * as lark from '@larksuiteoapi/node-sdk';
import { requestAxios } from '@/components/server/utils/request';
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<any>
) {
  const { id }: { id?: string } = req.query;
  const { download }: { download?: string } = req.query;
  const client = new lark.Client({
    appId: process.env.feishu_appid || '',
    appSecret: process.env.eishu_appkey || '',
  });
  const { headers, params, data, path } = await client.formatPayload(
    { path: { file_token: id } },
    {}
  );
  return requestAxios(
    'https://open.feishu.cn/open-apis/drive/v1/files/' + id + '/download',
    { method: 'GET', headers, responseType: 'arraybuffer' }
  ).then((resp) => {
    const header = resp.headers;
    for (const x in header) {
      if (!download && x == 'content-disposition') {
        continue;
      }
      res.appendHeader(x, header[x]);
    }
    res.send(resp.data);
  });
}
